<template>
  <div class="infor">
    <div class="infitem">
      <h1>上传考生信息</h1>
      <div class="infchildren">
        <h2>信息录入</h2>
        <el-form
          ref="createExaminForm"
          :model="createExaminForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          @submit.native.prevent
        >
          <div style="padding: 10px">
            <el-form-item label="考试批次" prop="region3">
              <el-select
                v-model="createExaminForm.region3"
                placeholder="请选择考试批次"
                style="width: 74%; float: left"
              >
                <el-option
                  v-for="(bcth, i) in bacth"
                  :key="i"
                  :label="bcth.batchName"
                  :value="bcth.batchId"
                ></el-option>
              </el-select>
              <el-button
                style="float: right; width: 25%"
                @click="dialogFormVisible = true"
              >
                添加批次
              </el-button>
            </el-form-item>

            <el-form-item label="上传照片" prop="poto">
              <el-upload
                ref="upload"
                class="upload-demo"
                action=""
                accept="image/jpeg"
                :file-list="fileList"
                :show-file-list="false"
                :http-request="httpFile"
                :on-progress="onProgress"
                multiple
                :limit="10"
                :on-change="changeFile"
                :auto-upload="false"
                :on-success="onSuccess"
                :on-exceed="handleExceed"
              >
                <i class="el-icon-plus avatar-uploader-icon">
                  <p>上传</p>
                </i>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
              <div class="ssll">
                <img src="../../assets/moren.png" alt="" />
                <p>示例图</p>
              </div>
            </el-form-item>
            <el-form-item label="上传文档" prop="txte">
              <el-upload
                ref="upload2"
                class="upload-demo"
                action=""
                :http-request="httpFile2"
                :auto-upload="false"
                :show-file-list="false"
                :limit="1"
                accept=".txt"
                :on-change="changeFile2"
                :on-exceed="handleExceed2"
                :file-list="fileList2"
                @click.native.stop="clickDel($refs.upload2)"
              >
                <i class="el-icon-plus avatar-uploader-icon">
                  <p>上传</p>
                </i>

                <div slot="tip" class="el-upload__tip">
                  只能上传.txt文件，且不超过3M
                </div>
              </el-upload>
              <div class="ssll">
                <i class="el-icon-document"></i>
                <p style="margin-top: -33px">示例</p>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button
                style="margin-left: -35%"
                type="primary"
                @click="submitForm('createExaminForm')"
              >
                上传
              </el-button>
            </el-form-item>
            <!-- <input
              id="infile"
              type="file"
              name=""
              placeholder="上传文件"
              multiple
              action="https://jsonplaceholder.typicode.com/posts/"
              @change="infild($event)"
            /> -->
          </div>
        </el-form>
      </div>

      <el-dialog
        v-dialogDrag
        title="添加批次"
        :visible.sync="dialogFormVisible"
      >
        <el-form
          ref="dialogForm"
          :model="dialogForm"
          :rules="rules"
          @submit.native.prevent
        >
          <el-form-item
            label="批次名称："
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input v-model="dialogForm.name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false"> 取 消 </el-button>
          <el-button type="primary" @click="submitbatch('dialogForm')">
            确 定
          </el-button>
        </div>
      </el-dialog>
    </div>
    <div class="infitem">
      <h1>系统录入结果</h1>
      <el-table
        :data="gert"
        class="tablejg"
        style="
          width: 100%;
          max-height: 680px;
          overflow-y: scroll;
          -ms-overflow-style: none;
          scrollbar-width: none;
        "
      >
        <el-table-column prop="name" label="文件名称" width="220px">
        </el-table-column>
        <el-table-column prop="size" label="文件大小">
          <template slot-scope="scope">
            {{ (scope.row.size / 1024).toFixed(1) + "Kb" }}
          </template>
        </el-table-column>

        <el-table-column prop="status" label="上传状态">
          <template slot-scope="scope">
            <div>
              <el-progress
                :status="
                  scope.row.percentage == 100
                    ? 'success'
                    : scope.row.isSuccess == 2
                    ? 'exception'
                    : null
                "
                :percentage="scope.row.percentage"
              ></el-progress>
            </div>
            <span v-if="scope.row.percentage != 100"> 等待中</span>
            <span v-else> 完成</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { getBatch, addBatch } from "@/api";
export default {
  data() {
    return {
      fileData: "", // 文件上传数据（多文件合一）
      uploadData: {
        dataFile: {
          // 批次,
        },
      },
      fileList: [], // upload多文件数组
      fileList2: [], // upload2文件
      gert: [], // 集合
      gert2: [], // 集合
      logo: [],
      bacth: [{ batchName: "222", batchId: 1101 }], //批次列表
      percent: 0,
      getBatchlist: function () {
        getBatch().then((res) => {
          this.bacth = res.data;
        });
      },
      rules: {
        name: [
          { required: false, message: "请输入班次名称", trigger: "change" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "blur",
          },
        ],
        region3: [
          { required: true, message: "请选择考试批次", trigger: "change" },
        ],
        poto: [
          {
            message: "请上传最少一张图片",
            trigger: "change",
            required: true,
          },
        ],
        txte: [
          {
            message: "请上传文档",
            trigger: "change",
            required: true,
          },
        ],
      },
      createExaminForm: {
        region3: "",
        name: "",
        poto: [],
        txte: [],
      },
      dialogForm: {
        name: "",
      },
      formLabelWidth: "120px",
      dialogFormVisible: false,
    };
  },
  mounted() {
    this.getBatchlist();
  },
  methods: {
    clickDel() {
      // this.gert2=[]
    },

    // 添加批次
    submitbatch(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogForm.name != "") {
            addBatch({
              batchName: this.dialogForm.name,
            })
              .then((res) => {
                console.log(res);
                this.$message({
                  message: "恭喜你，添加成功!",
                  type: "success",
                });
                this.getBatchlist();
              })
              .catch((err) => {
                console.log(err);
                this.$message.error("添加失败!");
              });
            this.dialogFormVisible = false;
          } else {
            this.$message({
              message: "请输入批次名称!",
              type: "warning",
            });
          }
        }
      });
    },

    onProgress(file) {
      console.log("onProgress");
      this.percent = file.percent;
    },
    onSuccess(res) {
      console.log("onSuccess");
      console.log(res);
    },

    // 文件状态改变时 文件上传
    changeFile(file, fileList) {
      const isJPG = file.raw.type === "image/jpeg";
      const isLt100K = file.size / 1024 < 100;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      } else if (!isLt100K) {
        this.$message({
          duration: 3000,
          message: `图片为"${file.name}"大小不能超过 100Kb!`,
          type: "error",
        });
      } else {
        this.createExaminForm.poto = fileList;
        this.gert.forEach((item) => {
          console.log(item);
        });
        this.gert.push(file);
        this.gert2.push(file);
        this.$refs.createExaminForm.clearValidate("poto"); // 取消提示信息
      }

      //  let list = this.$refs.upload.uploadFiles || [];
    },
    changeFile2(file, fileList2) {
      console.log(file);
      this.createExaminForm.txte = fileList2;
      // console.log();
      this.gert.unshift(file);
      this.gert2.unshift(file);
      this.$refs.createExaminForm.clearValidate("txte"); // 取消提示信息

      // this.fileData.append("files", text.raw);
    },

    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    handleExceed2() {
      this.$message.warning(`当前限制选择 1 个文件`);
    },

    httpFile() {
      console.log("httpFile");
      this.fileData = new FormData();
      this.gert2.forEach((item) => {
        return this.fileData.append("files", item.raw);
      });
    },
    httpFile2() {
      console.log("httpFile2");
      this.fileData.append("files", this.createExaminForm.txte[0].raw);
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$refs.upload.submit(); // 提交调用httpFile函
          // console.log(Object.prototype.toString.call(this.fileData) );
          if (
            Object.prototype.toString.call(this.fileData) == "[object FormData]"
          ) {
            // this.$refs.upload2.submit(); // 提交调用httpFile2函数
            // let config = {headers: {'Content-Type': 'multipart/form-data', "responseType": 'blob'}}

            let config = {
              timeout: 10000, //设置超时时长
              onUploadProgress: (progressEvent) => {
                let num =
                  ((progressEvent.loaded / progressEvent.total) * 100) | 0; //百分比
                this.$refs.upload.onProgress({ percent: num }); //进度条
              },
            };
            this.$axios
              .post(
                `/platform/management/personnelManage/uploadImageTxt?batchId=${this.createExaminForm.region3}`,
                this.fileData,
                config,
                {
                  headers: {
                    Authorization: localStorage.getItem("Authorization"),
                  },
                }
              )
              .then((res) => {
                if (res.data.result_code === 200) {
                  this.$message({
                    message: "上传成功",
                    type: "success",
                  });
                  this.fileList = [];
                  this.fileList2 = [];
                  this.$refs.upload.onSuccess(res.data);
                  this.gert.forEach((item) => {
                    item.percentage = 100;
                  });
                  this.fileData = "";
                  this.gert2 = [];
                } else {
                  this.$message({
                    message: res.data.msg,
                    type: "error",
                  });
                }
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            this.$message.warning("您没有选择图片或文件");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.infor {
  display: flex;
  flex-direction: row;
  height: auto;
  .infitem {
    flex: 1;
    min-height: 86vh;
    background: #fff;
    &:last-of-type {
      margin-left: 20px;
    }
    h1 {
      font-size: 28px;
      padding: 10px 0;
      border-bottom: 2px solid #008060;
    }
    .infchildren {
      position: relative;
      top: 25px;
      left: 50%;
      width: 85%;
      min-width: 500px;
      box-shadow: 0 0 14px -5px #ddd;
      transform: translateX(-50%);
      background-color: #f1f1f1;
      h2 {
        padding: 8px 10px;
        background: #008060;
        color: white;
        font-size: 16px;
        text-align: left;
        margin-bottom: 15px;
      }
    }

    .upload-demo {
      .el-upload__tip {
        text-align: left;
        color: #aaa;
        width: 55%;
        position: absolute;
        top: 91%;
        right: 14%;
      }

      p {
        line-height: 20px;
        margin-top: -13px;
        color: #bbb;
        font-size: 14px;
      }
    }
    .ssll {
      width: 150px;
      border: 1px dashed #d9d9d9;
      height: 170px;
      overflow: hidden;
      float: left;
      background-color: #fff;
      img {
        width: 90%;
        margin: 0 auto;
        height: 80%;
      }

      p {
        line-height: 20px;
        margin-top: -13px;
        color: #bbb;
        font-size: 14px;
      }
      i {
        font-size: 100px;
        color: #008060;
        line-height: 170px;
      }
    }
    .upload-demo .avatar-uploader-icon p {
      margin-top: -33px;
      color: #666;
    }
    .el-form-item {
      margin-bottom: 40px;
    }

    .el-table td,
    .el-table th {
      padding: 0;
    }
  }

  .upload-demo .el-upload-list {
    position: absolute;
    display: none;
    top: 50%;
    right: 20%;
  }
  .active {
    background: #008060;
  }
}
table tbody tr td {
  padding: 0;
}
html::-webkit-scrollbar {
  display: none;
  scroll-margin: 0;
}
html {
  scrollbar-width: none;
}
</style>
